<!-- 
- 项目管理:
	- 显示一个项目列表. 项目条目可多行显示, 紧跟着小括号内显示该项目的总耗时, 最右边有个向右的小箭头.
	- 创建: 项目的最下方, 显示一个输入框, 输入框的 placeholder 为 "输入项目名称并点击右侧加号添加项目". 输入框的右侧为圆形加号按钮, 点击创建项目.
	- 删除: 长按项目条目, 弹出项目的删除确认提示.
	- 修改: 点击项目条目, 项目条目变为可编辑状态(多行编辑), 同时右侧显示确认按钮, 可以修改项目名称. 修改完成后, 点击确认修改.

- 待办管理:
	- 点击项目条目右边的小箭头, 展开显示该项目下的待办列表, 同时箭头改为向下, 待办列表比项目缩进一些.
	- 创建: 展开的待办列表最下方, 显示一个输入框, 输入框的 placeholder 为 "输入待办名称并点击右侧加号添加待办". 输入框的右侧为圆形加号按钮, 点击创建待办.
	- 删除: 长按待办条目, 弹出待办的删除确认提示.
	- 修改: 点击待办条目, 待办条目变为可编辑状态(多行编辑), 同时右侧显示确认按钮, 可以修改待办名称. 修改完成后, 点击确认修改.
-->

<template>
	<view class="project-container">
		<!-- 首次加载状态 -->
		<view class="full-screen" v-if="projectStore.currentPage === 1 && !projectStore.isLoaded">
			<loading-state 
				style="flex:1" 
				mode="fullscreen" 
				:loading="projectStore.isLoading"
				:error="projectStore.isError"
				@retry="retryFetchData" 
			/>
		</view>
		<template v-else-if="projectStore.isLoaded">
			<!-- 无数据状态 -->
			<view v-if="projectStore.projects.length === 0" class="full-screen">
				<loading-state 
					style="flex:1" 
					mode="fullscreen" 
					:empty="true"
				/>
			</view>
			<!-- 有数据时的列表视图 -->
			<view v-else class="project-content">
				<scroll-view 
					class="scroll-view" 
					scroll-y 
					@scrolltolower="onReachBottom"
					:scroll-top="scrollTop"
				>
					<uni-list style="overflow: hidden;">
						<template v-for="project in projectStore.projects" :key="project.id">
							<uni-list-item class="project-item">
								<template #body style="width:100%">
									<!-- 项目行(普通显示) -->
									<view v-if="!project.isEditing" class="project-row" @longpress="showProjectActions(project)">
										<view class="project-info" @click="toggleExpand(project)">
											<text class="project-name">{{ project.name }}</text>
											<text class="project-time">（{{ formatTime(project.totalTime) }}）</text>
										</view>
										<view class="arrow">
											<text>{{ project.isExpanded ? '▼' : '▶' }}</text>
										</view>
									</view>
									<!-- 项目行(编辑状态) -->
									<view v-else class="project-row">
										<view class="project-edit">
											<textarea v-model="project.editName" auto-height class="project-name edit-input" />
											<view class="confirm-btn" @click="confirmEditProject(project)">✔</view>
										</view>
									</view>
									<!-- 待办列表 -->
									<view v-if="project.isExpanded" class="todo-list">
										<view v-for="todo in todoStore.todosByProject[project.id]?.todos || []" 
											:key="todo.id" 
											class="todo-item"
											@longpress="showTodoActions(project, todo)">
											<view v-if="!todo.isEditing" class="todo-info">
												<view class="todo-info-left">
													<text class="todo-name">{{ todo.name }}</text>
													<text class="todo-time">（{{ formatTime(todo.totalTime) }}）</text>
												</view>
												<view class="todo-timer">
													<image src="/static/start.png" mode="aspectFit" class="timer-icon" @click="startTimer(project.id, todo.id)"></image>
												</view>
											</view>
											<view v-else class="todo-edit">
												<textarea v-model="todo.editName" auto-height class="edit-input" />
												<view class="confirm-btn" @click="confirmEditTodo(project, todo)">✔</view>
											</view>
										</view>
										
										<!-- 添加任务按钮 -->
										<view v-if="!project.isAddingTodo" class="add-todo-btn" @click="showAddTodoInput(project)">
											<text class="add-icon">＋</text>
											<text class="add-text">添加任务</text>
										</view>
										
										<!-- 添加任务输入框 -->
										<view v-else class="add-todo-input">
											<textarea v-model="newTodoName[project.id]" 
												class="edit-input" 
												placeholder="输入任务名称"
												auto-focus
												@blur="hideAddTodoInput(project)" />
											<view class="confirm-btn" @click="addTodo(project)">✔</view>
										</view>
									</view>
								</template>
							</uni-list-item>
						</template>
					</uni-list>

					<!-- 加载更多 -->
					<loading-state 
						mode="footer" 
						:loading="projectStore.isLoading"
						:error="projectStore.isError"
						:no-more="!projectStore.hasMore"
						@retry="retryFetchData" 
					/>
				</scroll-view>
			</view>

		</template>
		

		<!-- 添加项目按钮 -->
		<view class="add-project-btn" @click="showAddProjectPopup">
			<text class="add-icon">＋</text>
			<text class="add-text">添加项目</text>
		</view>

		<!-- 项目操作弹窗 -->
		<uni-popup ref="projectPopup" type="bottom">
			<view class="popup-content">
				<view class="popup-item" @click="handleProjectAction('edit')">编辑项目</view>
				<view class="popup-item" @click="handleProjectAction('delete')">删除项目</view>
				<view class="popup-item" @click="handleProjectAction('addMember')">添加成员</view>
				<view class="popup-item cancel" @click="hideProjectPopup">取消</view>
			</view>
		</uni-popup>

		<!-- 任务操作弹窗 -->
		<uni-popup ref="todoPopup" type="bottom">
			<view class="popup-content">
				<view class="popup-item" @click="handleTodoAction('edit')">编辑任务</view>
				<view class="popup-item" @click="handleTodoAction('delete')">删除任务</view>
				<view class="popup-item cancel" @click="hideTodoPopup">取消</view>
			</view>
		</uni-popup>

		<!-- 添加项目弹窗 -->
		<uni-popup ref="addProjectPopup" type="center">
			<uni-popup-dialog mode="input" v-model="newProjectName" title="创建项目" :duration="2000" :before-close="true" @close="closeProjectModal" @confirm="confirmAddProject"></uni-popup-dialog>
		</uni-popup>

		<!-- 添加项目成员弹窗 -->
		<uni-popup ref="addProjectMemberPopup" type="center">
			<uni-popup-dialog cancelText="取消" confirmText="确认" title="添加项目成员" content="" :before-close="true" @close="closeAddProjectMemberModal" @confirm="addProjectMember">
				<view class="popup-content" style="width: 600rpx;">
					<view style="color: #888; font-size: 26rpx; margin-bottom: 20rpx;">
						目前仅支持按照邮箱搜索对方账号, 如果对方不是邮箱登录用户, 请提醒对方先在"我的"页面绑定邮箱.
					</view>
					<view style="display: flex; align-items: center; margin-bottom: 20rpx; width: 100%;">
						<input v-model="addProjectMemberEmail" placeholder="输入对方邮箱" class="popup-input input" style="flex:1;" />
						<button @click="searchProjectMember" style="margin-left: 10rpx; min-width: 100rpx;" size="mini">搜索</button>
					</view>
					<!-- 搜索结果 -->
					<view style="width: 100%; height: 28rpx;">
						<view v-if="addProjectMemberSearched">
							<view v-if="addProjectMemberUser" style="color: #333; font-size: 28rpx; margin-bottom: 10rpx;">
								找到: {{ addProjectMemberUser.nickName || addProjectMemberUser.username }}
							</view>
							<view v-else style="color: #e53935; font-size: 28rpx; margin-bottom: 10rpx;">
								账号不存在
							</view>
						</view>
					</view>
				</view>
			</uni-popup-dialog>
		</uni-popup>

		<uni-popup ref="deleteProjectPopup" type="dialog">
			<uni-popup-dialog cancelText="取消" confirmText="确认" title="提示" content="确定要删除该项目吗" @confirm="confirmDeleteProject"
				@close="cancelDeleteProject"></uni-popup-dialog>
		</uni-popup>

		<uni-popup ref="deleteTodoPopup" type="dialog">
			<uni-popup-dialog cancelText="取消" confirmText="确认" title="提示" content="确定要删除该任务吗" @confirm="confirmDeleteTodo"
				@close="cancelDeleteTodo"></uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script setup>
import { ref, onMounted, nextTick, computed } from 'vue';
import { useProjectStore } from '../../stores/project';
import { useTodoStore } from '../../stores/todo';
import { useUserStore } from '../../stores/user';
import LoadingState from '../../components/loadingState';

// stores
const projectStore = useProjectStore();
const todoStore = useTodoStore();
const userStore = useUserStore();

// reactive state
const newProjectName = ref('');
const newTodoName = ref({}); // { [projectId]: '' }
const loadingStatus = ref('ready'); // 'ready' | 'loading' | 'error' | 'noData' | 'success' | 'noMore'

//添加项目弹框
const addProjectPopup = ref(null)

// 项目操作弹窗
const projectPopup = ref(null)
// 当前选中的项目
const currentProject = ref(null)

// 任务操作弹窗
const todoPopup = ref(null)
// 当前选中的认为
const currentTodo = ref(null)

// 删除弹窗ref
const deleteProjectPopup = ref(null)
const deleteTodoPopup = ref(null)

// 添加项目成员相关状态
const addProjectMemberPopup = ref(null);
const addProjectMemberEmail = ref('');
const addProjectMemberUser = ref(null); // {nickname: string, ...}
const addProjectMemberSearched = ref(false); // 已经搜索过, 但未必找到
const addProjectMemberAdding = ref(false);

// 滚动相关
const scrollTop = ref(0);

// methods
const startTimer = (projectId, todoId) => {
	console.log(`startTimer_. projectId: ${projectId}, todoId: ${todoId}`);

	uni.setStorageSync('startClockParams', { projectId, todoId, startClock: true });
	uni.switchTab({
		url: '/pages/clock/clock'
	});
};

// 格式化时间, 返回浮点数表示的小时数, 精确到小数点后1位
// return: string
const formatTime = (minutes) => {
	// 浮点数表示的小时数, 精确到小数点后1位
	const h = minutes / 60;
	return h.toFixed(1) + 'h';
};

const toggleExpand = (project) => {
	project.isExpanded = !project.isExpanded;
	if (project.isExpanded) {
		// 展开项目时获取待办列表
		todoStore.fetchTodos(project.id);
	}
};

const startEditProject = (project) => {
	project.isEditing = true;
	project.editName = project.name;
};

const confirmEditProject = (project) => {
	// 调用后台接口更新项目名称
	projectStore.updateProject({id: project.id, name: project.editName});
	project.name = project.editName;
	project.isEditing = false;
};

const showDeleteProject = (projectId) => {
	deleteProjectPopup.value.open()
};

const showAddMemberPopup = (projectId) => {
	addProjectMemberEmail.value = '';
	addProjectMemberUser.value = null;
	addProjectMemberSearched.value = false;
	addProjectMemberAdding.value = false;
	addProjectMemberPopup.value.open();
};

const confirmDeleteProject = async () => {
	try {
		await projectStore.deleteProject(currentProject.value?.id);
		currentProject.value = {}
		uni.showToast({
			title: '删除成功',
			icon: 'success'
		})
		// 刷新项目列表
		fetchData();
	} catch(error) {
		uni.showToast({
			title: '删除失败:' + error.message,
			icon: 'none'
		})
	}
};

const cancelDeleteProject = () => {
	currentProject.value = {}
};

const addProject = async() => {
	console.log('addProject_', newProjectName.value);
	if (!newProjectName.value.trim()) return;
	try{
		// 调用后台接口添加项目
		await projectStore.addProject({name: newProjectName.value});
		newProjectName.value = '';
		uni.showToast({
			title: '创建成功',
			icon: 'success'
		})
		//刷新项目列表
		fetchData();
	}catch(error){
		uni.toast({
			title: '创建失败' + error.message,
			icon: 'error'
		})
	}
	
};

const startEditTodo = (project, todo) => {
	todo.isEditing = true;
	todo.editName = todo.name;
};

const confirmEditTodo = (project, todo) => {
	// 调用后台接口更新待办名称
	todoStore.updateTodo(project.id, todo.id, todo.editName);
	todo.name = todo.editName;
	todo.isEditing = false;
};

const showDeleteTodo = (projectId, todoId) => {
	deleteTodoPopup.value.open();
};

const confirmDeleteTodo = () => {
	const { project, todo } = currentTodo.value;
	// 调用后台接口删除待办
	todoStore.deleteTodo(project?.id, todo?.id);
	currentTodo.value = {}
	uni.showToast({
      title: '删除成功',
      icon: 'success'
    })
};

const cancelDeleteTodo = () => {
	currentTodo.value = {}
};

const showProjectActions = (project) => {
	console.log('showProjectActions_  project', project);
	currentProject.value = project
	projectPopup.value.open()
}

const hideProjectPopup = () => {
	projectPopup.value.close()
}

const handleProjectAction = (action) => {
	if (!currentProject.value) return
	hideProjectPopup()
	
	switch (action) {
		case 'edit':
			startEditProject(currentProject.value)
			break
		case 'delete':
			showDeleteProject(currentProject.value)
			break
		case 'addMember':
			showAddMemberPopup(currentProject.value)
			break
	}
}

const showTodoActions = (project, todo) => {
	currentTodo.value = { project, todo }
	todoPopup.value.open()
}

const hideTodoPopup = () => {
	todoPopup.value.close()
}

const handleTodoAction = (action) => {
	if (!currentTodo.value) return
	hideTodoPopup()

	const { project , todo } = currentTodo.value

	switch (action) {
		case 'edit':
			startEditTodo(project,todo)
			break
		case 'delete':
			showDeleteTodo(project,todo)
			break
	}
}

const showAddProjectPopup = () => {
	newProjectName.value = ''
	addProjectPopup.value.open()
}

const hideAddProjectPopup = () => {
	addProjectPopup.value.close()
}

const confirmAddProject = () => {
	if (!newProjectName.value.trim()) {
		uni.showToast({
			title: '请输入项目名称',
			icon: 'none'
		})
		return
	}
	addProject()
	hideAddProjectPopup()
}

const closeProjectModal = () => {
	newProjectName.value = ''
	hideAddProjectPopup()
}

// 任务创建相关
const showAddTodoInput = (project) => {
	project.isAddingTodo = true
	newTodoName.value[project.id] = ''
}

const hideAddTodoInput = (project) => {
	project.isAddingTodo = false
}

const addTodo = (project) => {
	const name = newTodoName.value[project.id]
	if (!name || !name.trim()) {
		uni.showToast({
			title: '请输入任务名称',
			icon: 'none'
		})
		return
	}
	todoStore.addTodo(project.id, name)
	hideAddTodoInput(project)

	uni.showToast({
      title: '创建成功',
      icon: 'success'
    })
}

// 关闭弹窗
const closeAddProjectMemberModal = () => {
	addProjectMemberPopup.value.close();
};

// 按邮箱搜索用户成员
const searchProjectMember = async () => {
	addProjectMemberSearched.value = false;
	addProjectMemberUser.value = null;
	if (!addProjectMemberEmail.value.trim()) {
		uni.showToast({ title: '请输入邮箱', icon: 'none' });
		return;
	}
	// 调用 user store 的 fetchUserByEmail
	const user = await userStore.fetchUserByEmail(addProjectMemberEmail.value.trim());
	if (user) {
		console.log('searchProjectMember_. Found user', user);
		addProjectMemberUser.value = user;
	} else {
		console.log('searchProjectMember_. Not found user');
		// uni.showToast({ title: '用户不存在', icon: 'none' });
		addProjectMemberUser.value = null;
	}
	addProjectMemberSearched.value = true;
};

// 添加项目成员
const addProjectMember = async () => {
	if (!addProjectMemberUser.value) {
		uni.showToast({
			title: '请先搜索用户',
			icon: 'none'
		})
		return;
	}

	addProjectMemberAdding.value = true;

	try {
		await projectStore.addProjectMember(currentProject.value.id, addProjectMemberUser.value.id);
		closeAddProjectMemberModal();
		uni.showToast({
			title: "添加成功",
			icon: 'success'
		});

		// 刷新项目列表
		fetchData();

	} catch (error) {
		uni.showToast({
			title: error.message,
			icon: 'none'
		});
		console.error('### addProjectMember_ error:', error);
	}
};

// 修改 onReachBottom 函数
const onReachBottom = () => {
	console.log('onReachBottom_');
	//如果没有更多数据，则不加载
	if (!projectStore.hasMore) return;
	//如果正在加载，则不加载
	if (projectStore.isLoading) return;
	//如果状态是失败，则重新加载
	if (projectStore.isError) {
		retryFetchData();
		return;
	}
	//加载更多
	fetchData(projectStore.currentPage + 1);
};

const retryFetchData = async () => {
	const page = projectStore.currentPage;
	fetchData(page);
}


const fetchData = async (page = 1) => {
	try {
		await projectStore.fetchProjects(page);
	} catch(error) {
		console.error('fetchData_ error:', error);
		uni.showToast({
			title: '加载失败',
			icon: 'none'
		});
	}
}

// lifecycle hooks
onMounted(async () => {
	fetchData();
});
</script>

<style lang="scss">
.project-container {
	width: 100%;
	height: 100vh;
	background-color: #F8F8F8;
	display: flex;
	flex-direction: column;
	overflow: hidden;

	.full-screen{
		flex: 1;
		display: flex;
		flex-direction: column;
		overflow: hidden;
	}
	
	.project-content {
		flex: 1;
		padding: 20rpx;
		display: flex;
		flex-direction: column;
		overflow: hidden;
		
		.scroll-view {
			flex: 1;
			height: 0; // 重要：让scroll-view填充剩余空间
		}
		
		.project-item {
			margin-bottom: 10rpx;
			.project-row {
				width: 100%;
				display: flex;
				align-items: center;
				.project-info {
					display: flex;
					align-items: center;
					.project-name {
						font-size: 30rpx;
						font-weight: 500;
						word-break: break-all;
					}
					.project-time {
						margin-left: 10rpx;
						color: #888;
						font-size: 24rpx;
					}
				}
				.project-edit {
					width: 100%;
					display: flex;
					align-items: center;
					margin-bottom: 10rpx;
					.edit-input {
						flex: 1;
						min-height: 40rpx;
						font-size: 28rpx;
						margin-right: 10rpx;
						padding: 20rpx;
						border: 1rpx solid gray;
					}
					.confirm-btn {
						color: #fff;
						background: #4caf50;
						border-radius: 50%;
						width: 40rpx;
						height: 40rpx;
						display: flex;
						align-items: center;
						justify-content: center;
						font-size: 28rpx;
					}
				}
				.arrow {
					margin-left: auto;
					font-size: 32rpx;
					color: #888;
					padding: 0 10rpx;
					cursor: pointer;
				}
			}
			.todo-list {
				margin-left: 40rpx;
				.todo-item {
					display: flex;
					align-items: center;
					margin-bottom: 10rpx;
					width: 100%;
					.todo-info {
						background-color: #def;
						display: flex;
						justify-content: space-between;
						align-items: center;
						width: 100%;
						padding: 20rpx;
						margin-bottom: 10rpx;
						.todo-info-left {
							display: flex;
							align-items: center;
							.todo-name {
								font-size: 26rpx;
								word-break: break-all;
							}
							.todo-time {
								margin-left: 8rpx;
								color: #888;
								font-size: 22rpx;
							}
						}
						.todo-timer {
							border-radius: 50%;
							.timer-icon {
								width: 30rpx;
								height: 30rpx;
							}
						}
					}
					.todo-edit {
						display: flex;
						justify-content: space-between;
						align-items: center;
						width: 100%;
						.edit-input {
							min-height: 40rpx;
							font-size: 24rpx;
							margin-right: 10rpx;
							padding: 20rpx;
							border: 1rpx solid #eee;
						}
						.confirm-btn {
							color: #fff;
							background: #4caf50;
							border-radius: 50%;
							width: 36rpx;
							height: 36rpx;
							display: flex;
							align-items: center;
							justify-content: center;
							font-size: 24rpx;
						}
					}
				}
				.add-todo-btn {
					display: flex;
					align-items: center;
					padding: 20rpx;
					margin: 10rpx 0;
					background-color: #f8f8f8;
					border-radius: 8rpx;
					
					.add-icon {
						font-size: 32rpx;
						color: #2196f3;
						margin-right: 10rpx;
					}
					
					.add-text {
						font-size: 26rpx;
						color: #2196f3;
					}
					
					&:active {
						background-color: #f0f0f0;
					}
				}
				.add-todo-input {
					display: flex;
					align-items: flex-start;
					padding: 20rpx;
					margin: 10rpx 0;
					background-color: #fff;
					border-radius: 8rpx;
					box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.1);
					
					.edit-input {
						flex: 1;
						min-height: 60rpx;
						font-size: 26rpx;
						padding: 10rpx;
						margin-right: 10rpx;
						border: 1rpx solid #eee;
						border-radius: 6rpx;
					}
					
					.confirm-btn {
						color: #fff;
						background: #4caf50;
						border-radius: 50%;
						width: 40rpx;
						height: 40rpx;
						display: flex;
						align-items: center;
						justify-content: center;
						font-size: 28rpx;
					}
				}
			}
		}
	}
	
	.add-project-btn {
		display: flex;
		align-items: center;
		justify-content: center;
		margin: 20rpx;
		padding: 20rpx;
		background-color: #fff;
		border-radius: 12rpx;
		box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.1);
		
		.add-icon {
			font-size: 36rpx;
			color: #2196f3;
			margin-right: 10rpx;
		}
		
		.add-text {
			font-size: 28rpx;
			color: #2196f3;
		}
	}
}
.popup-mask {
	position: fixed;
	left: 0;
	top: 0;
	width: 100vw;
	height: 100vh;
	background: rgba(0,0,0,0.3);
	display: flex;
	align-items: center;
	justify-content: center;
	z-index: 1000;
	.popup-box {
		background: #fff;
		border-radius: 16rpx;
		padding: 40rpx 60rpx;
		text-align: center;
		.popup-actions {
			display: flex;
			justify-content: space-around;
			margin-top: 30rpx;
			.popup-btn {
				padding: 10rpx 30rpx;
				background: #2196f3;
				color: #fff;
				border-radius: 10rpx;
				font-size: 28rpx;
				cursor: pointer;
			}
		}
	}
}

.popup-content {
	background-color: #fff;
	padding: 20rpx;
	border-radius: 20rpx 20rpx 0 0;
}

.popup-header {
	padding: 20rpx;
	text-align: center;
	border-bottom: 1rpx solid #eee;
	
	.popup-title {
		font-size: 32rpx;
		font-weight: 500;
	}
}

.popup-input {
	// padding: 30rpx;
	
	.input {
		width: 100%;
		height: 80rpx;
		padding: 0 20rpx;
		border: 1rpx solid #eee;
		border-radius: 8rpx;
		font-size: 28rpx;
	}
}

.popup-buttons {
	display: flex;
	padding: 20rpx;
	border-top: 1rpx solid #eee;
	
	.popup-btn {
		flex: 1;
		height: 80rpx;
		line-height: 80rpx;
		text-align: center;
		font-size: 28rpx;
		
		&.cancel {
			color: #666;
			border-right: 1rpx solid #eee;
		}
		
		&.confirm {
			color: #2196f3;
		}
	}
}

.popup-item {
	padding: 30rpx;
	text-align: center;
	border-bottom: 1rpx solid #eee;
	font-size: 28rpx;
	
	&.cancel {
		color: #999;
		border-bottom: none;
	}
}

.project-row {
	.project-info {
		flex: 1;
		display: flex;
		align-items: center;
		padding: 20rpx;
		// 添加点击反馈效果
		&:active {
			background-color: rgba(0, 0, 0, 0.05);
		}
	}
}
</style> 